package com.suweia.pr.plugin;

import com.suweia.pr.util.OSinfo;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 15-12-12
 * Time: 下午11:18
 * To change this template use File | Settings | File Templates.
 */
@Mojo(name = "version-update")
public class VersionUpdater extends AbstractMojo {

    @Parameter( property = "version-update.onlyRelease", defaultValue = "true" )
    private boolean onlyRelease;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec("git branch");
            InputStream in = process.getInputStream();
            byte[] bts=new byte[1024];
            StringBuilder sb=new StringBuilder("");
            int length=0;
            while ((length=in.read(bts)) != -1) {
                if(OSinfo.isWindows()){
                    sb.append(new String(bts,0,length, "GBK"));
                }else {
                    sb.append(new String(bts,0,length, "UTF-8"));
                }
            }
            in.close();
            process.waitFor();

            getLog().info("branchs:\n"+sb.toString());

            //找出当前分支
            String currentBranch=null;
            String []branchs=sb.toString().split("\n");
            for(String branch:branchs){
                if(branch.startsWith("*")){
                    currentBranch=branch;
                    break;
                }
            }
            getLog().info("currentBranch->"+currentBranch);
            if(currentBranch==null){
                return;
            }
            String version=null;
            if(onlyRelease){
                if(currentBranch.contains("release")){
                    version=currentBranch.substring(2).replaceAll("/","_");
                }
                getLog().info("onlyRelease-true");
            }else{
                getLog().info("onlyRelease->false");
                version=currentBranch.substring(2).replaceAll("/","_");
            }

            if(version!=null){
                SAXReader saxReader=new SAXReader();
                Document document= null;
                try {
                    //InputStream inputStream = getClass().getClassLoader().getResourceAsStream("com/suweia/pb/template/servicebuild/pom/parent_pom.xml");
                    document = saxReader.read(new FileInputStream(new File("pom.xml")));
                    Element rootEl=document.getRootElement();

                    Element parentElement=rootEl.element("parent");
                    Element versionElement=rootEl.element("version");
                    if(parentElement!=null){
                        versionElement=parentElement.element("version");
                    }
                    if(versionElement==null){
                        if(parentElement!=null){
                            versionElement=parentElement.addElement("version");
                        }else {
                            versionElement=rootEl.addElement("version");
                        }
                    }
                    versionElement.setText(version);
                    //写入
                    // 美化格式
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter writer = new XMLWriter(new FileWriter(new File("pom.xml")),format);
                    writer.write( document );
                    writer.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                getLog().info("version updated");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
